﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;

namespace MMCInfo.Validations
{
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class DateOfBirthValidationAttribute : ValidationAttribute
    {
        public DateOfBirthValidationAttribute() :
            base("De opgegeven datum is ongeldig")
        {

        }

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return false;
            }
            string[] allowedFormats = { "dd-mm", "dd-mm-yyyy" };
            string date = (string)value;
            DateTime result;

            foreach (string format in allowedFormats)
            {
                try
                {
                    result = DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);
                    if(result.CompareTo(DateTime.Now)<0)
                    {
                        return true;
                    }
                }
                catch (FormatException)
                {
                    //Kon niet naar DateTime object zetten, dus verkeerde format
                }
            }

            //Geen geldige datum gegeven, false returnen
            return false;
        }
    }
}